/**
 * BoLe智能HR系统 - 界面布局修复JavaScript补丁
 * 处理动态布局调整、响应式行为和交互优化
 */

class LayoutFixes {
    constructor() {
        this.isInitialized = false;
        this.resizeTimeout = null;
        this.currentBreakpoint = this.getCurrentBreakpoint();
        
        this.init();
    }

    init() {
        if (this.isInitialized) return;
        
        console.log('🔧 初始化布局修复系统...');
        
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setupFixes());
        } else {
            this.setupFixes();
        }
        
        this.isInitialized = true;
    }

    setupFixes() {
        this.setupResponsiveHandlers();
        this.setupScrollOptimization();
        this.setupModalFixes();
        this.setupInputAreaFixes();
        this.setupTooltipFixes();
        this.setupAccessibilityFixes();
        
        // 初始化时执行一次布局检查
        this.handleResize();
        
        console.log('✅ 布局修复系统初始化完成');
    }

    // 获取当前断点
    getCurrentBreakpoint() {
        const width = window.innerWidth;
        if (width <= 480) return 'mobile';
        if (width <= 768) return 'tablet';
        if (width <= 1200) return 'desktop';
        return 'large';
    }

    // 响应式处理
    setupResponsiveHandlers() {
        window.addEventListener('resize', () => {
            // 防抖处理
            clearTimeout(this.resizeTimeout);
            this.resizeTimeout = setTimeout(() => {
                this.handleResize();
            }, 150);
        });

        // 监听屏幕方向变化
        if (screen && screen.orientation) {
            screen.orientation.addEventListener('change', () => {
                setTimeout(() => this.handleResize(), 200);
            });
        }
    }

    handleResize() {
        const newBreakpoint = this.getCurrentBreakpoint();
        const breakpointChanged = newBreakpoint !== this.currentBreakpoint;
        
        if (breakpointChanged) {
            console.log(`📱 断点切换: ${this.currentBreakpoint} → ${newBreakpoint}`);
            this.currentBreakpoint = newBreakpoint;
            
            // 触发断点变化事件
            document.dispatchEvent(new CustomEvent('breakpointChange', {
                detail: { 
                    old: this.currentBreakpoint, 
                    new: newBreakpoint 
                }
            }));
        }

        this.adjustLayout();
        this.adjustTextareas();
        this.adjustModals();
        this.adjustCharts();
    }

    // 动态布局调整
    adjustLayout() {
        const mainContent = document.querySelector('.main-content');
        if (!mainContent) return;

        const breakpoint = this.currentBreakpoint;
        
        // 根据断点调整布局
        switch (breakpoint) {
            case 'mobile':
                this.adjustMobileLayout();
                break;
            case 'tablet':
                this.adjustTabletLayout();
                break;
            case 'desktop':
                this.adjustDesktopLayout();
                break;
            case 'large':
                this.adjustLargeLayout();
                break;
        }
    }

    adjustMobileLayout() {
        // 确保手机端的触摸目标足够大
        const buttons = document.querySelectorAll('.btn');
        buttons.forEach(btn => {
            if (!btn.classList.contains('btn-lg')) {
                btn.style.minHeight = '44px';
                btn.style.minWidth = '44px';
            }
        });

        // 调整侧边栏为抽屉式
        const workbench = document.querySelector('.candidate-workbench');
        const panel = document.querySelector('.deep-info-panel');
        
        if (workbench) {
            workbench.style.position = 'relative';
            workbench.style.zIndex = '100';
        }
        
        if (panel) {
            panel.style.position = 'relative';
            panel.style.zIndex = '100';
        }
    }

    adjustTabletLayout() {
        // 平板端布局调整
        const sidebar = document.querySelector('.sidebar');
        if (sidebar) {
            sidebar.style.width = '100%';
            sidebar.style.maxWidth = '320px';
        }
    }

    adjustDesktopLayout() {
        // 桌面端布局恢复
        const workbench = document.querySelector('.candidate-workbench');
        const panel = document.querySelector('.deep-info-panel');
        
        if (workbench) {
            workbench.style.position = '';
            workbench.style.zIndex = '';
        }
        
        if (panel) {
            panel.style.position = '';
            panel.style.zIndex = '';
        }
    }

    adjustLargeLayout() {
        // 大屏幕优化
        const mainContent = document.querySelector('.main-content');
        if (mainContent && mainContent.classList.contains('dashboard')) {
            mainContent.style.maxWidth = '1400px';
            mainContent.style.margin = '0 auto';
        }
    }

    // 滚动优化
    setupScrollOptimization() {
        // 平滑滚动
        document.documentElement.style.scrollBehavior = 'smooth';
        
        // 优化长列表滚动性能
        const scrollContainers = document.querySelectorAll(
            '.chat-history, .candidate-list, .workbench-content, .panel-content'
        );
        
        scrollContainers.forEach(container => {
            // 添加惯性滚动
            container.style.webkitOverflowScrolling = 'touch';
            
            // 滚动性能优化
            container.style.willChange = 'scroll-position';
        });
    }

    // 文本域自适应
    adjustTextareas() {
        const textareas = document.querySelectorAll('textarea');
        
        textareas.forEach(textarea => {
            this.makeTextareaAutoResize(textarea);
        });
    }

    makeTextareaAutoResize(textarea) {
        if (textarea.dataset.autoResize) return; // 已经处理过
        
        textarea.dataset.autoResize = 'true';
        
        const adjust = () => {
            textarea.style.height = 'auto';
            const newHeight = Math.min(textarea.scrollHeight, 200); // 最大高度200px
            textarea.style.height = newHeight + 'px';
        };
        
        textarea.addEventListener('input', adjust);
        textarea.addEventListener('focus', adjust);
        
        // 初始调整
        adjust();
    }

    // 模态框修复
    setupModalFixes() {
        const modals = document.querySelectorAll('.modal');
        
        modals.forEach(modal => {
            // 防止背景滚动
            modal.addEventListener('show', () => {
                document.body.style.overflow = 'hidden';
            });
            
            modal.addEventListener('hide', () => {
                document.body.style.overflow = '';
            });
            
            // ESC键关闭
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && modal.style.display !== 'none') {
                    this.closeModal(modal);
                }
            });
        });
    }

    adjustModals() {
        const modals = document.querySelectorAll('.modal-content, .chart-modal-content, .candidate-modal-content');
        
        modals.forEach(modal => {
            const viewportHeight = window.innerHeight;
            const viewportWidth = window.innerWidth;
            
            // 确保模态框不超出视口
            if (this.currentBreakpoint === 'mobile') {
                modal.style.width = 'calc(100vw - 1rem)';
                modal.style.height = 'calc(100vh - 2rem)';
                modal.style.margin = '0.5rem';
            } else if (this.currentBreakpoint === 'tablet') {
                modal.style.width = 'calc(100vw - 2rem)';
                modal.style.maxHeight = 'calc(100vh - 4rem)';
                modal.style.margin = '2rem auto';
            }
        });
    }

    closeModal(modal) {
        modal.style.display = 'none';
        document.body.style.overflow = '';
        
        // 触发关闭事件
        modal.dispatchEvent(new CustomEvent('hide'));
    }

    // 输入区域修复
    setupInputAreaFixes() {
        const inputWrappers = document.querySelectorAll('.input-wrapper');
        
        inputWrappers.forEach(wrapper => {
            const input = wrapper.querySelector('input, textarea');
            const sendBtn = wrapper.querySelector('.send-btn, .btn');
            
            if (input && sendBtn) {
                // 确保按钮和输入框对齐
                wrapper.style.display = 'flex';
                wrapper.style.alignItems = 'flex-end';
                wrapper.style.gap = '0.5rem';
                
                input.style.flex = '1';
                sendBtn.style.flexShrink = '0';
            }
        });
    }

    // 图表调整
    adjustCharts() {
        const charts = document.querySelectorAll('.chart-container canvas');
        
        charts.forEach(canvas => {
            const container = canvas.closest('.chart-container');
            if (container && window.Chart) {
                // 触发Chart.js重新计算大小
                const chartInstance = window.Chart.getChart(canvas);
                if (chartInstance) {
                    chartInstance.resize();
                }
            }
        });
    }

    // 工具提示修复
    setupTooltipFixes() {
        const tooltipTriggers = document.querySelectorAll('[title]');
        
        tooltipTriggers.forEach(trigger => {
            if (this.currentBreakpoint === 'mobile') {
                // 在移动端移除title属性，因为悬停不可用
                const title = trigger.getAttribute('title');
                trigger.removeAttribute('title');
                trigger.dataset.originalTitle = title;
                
                // 添加点击显示提示
                trigger.addEventListener('click', (e) => {
                    this.showMobileTooltip(trigger, title);
                });
            }
        });
    }

    showMobileTooltip(element, text) {
        // 简单的移动端工具提示实现
        const tooltip = document.createElement('div');
        tooltip.className = 'mobile-tooltip';
        tooltip.textContent = text;
        tooltip.style.cssText = `
            position: absolute;
            background: #333;
            color: white;
            padding: 0.5rem;
            border-radius: 4px;
            font-size: 0.8rem;
            z-index: 1000;
            max-width: 200px;
            word-wrap: break-word;
        `;
        
        document.body.appendChild(tooltip);
        
        const rect = element.getBoundingClientRect();
        tooltip.style.left = rect.left + 'px';
        tooltip.style.top = (rect.bottom + 5) + 'px';
        
        setTimeout(() => {
            if (tooltip.parentNode) {
                tooltip.parentNode.removeChild(tooltip);
            }
        }, 3000);
    }

    // 无障碍修复
    setupAccessibilityFixes() {
        // 确保所有交互元素都有合适的焦点样式
        const interactiveElements = document.querySelectorAll(
            'button, a, input, textarea, select, [tabindex], [role="button"]'
        );
        
        interactiveElements.forEach(element => {
            if (!element.style.outline) {
                element.addEventListener('focus', () => {
                    element.style.outline = '2px solid var(--primary-color, #667eea)';
                    element.style.outlineOffset = '2px';
                });
                
                element.addEventListener('blur', () => {
                    element.style.outline = '';
                    element.style.outlineOffset = '';
                });
            }
        });
        
        // 为移动端添加触摸反馈
        if (this.currentBreakpoint === 'mobile') {
            interactiveElements.forEach(element => {
                element.addEventListener('touchstart', () => {
                    element.style.transform = 'scale(0.98)';
                });
                
                element.addEventListener('touchend', () => {
                    element.style.transform = '';
                });
            });
        }
    }

    // 公共方法：强制重新计算布局
    recalculateLayout() {
        this.handleResize();
    }

    // 公共方法：添加布局监听器
    onBreakpointChange(callback) {
        document.addEventListener('breakpointChange', callback);
    }

    // 公共方法：获取当前断点
    getBreakpoint() {
        return this.currentBreakpoint;
    }
}

// 自动初始化
if (typeof window !== 'undefined') {
    window.LayoutFixes = LayoutFixes;
    window.layoutFixes = new LayoutFixes();
    
    // 导出到全局，供其他脚本使用
    window.recalculateLayout = () => window.layoutFixes.recalculateLayout();
}

// 如果是Node.js环境，导出模块
if (typeof module !== 'undefined' && module.exports) {
    module.exports = LayoutFixes;
}





